import React from 'react'
import uPlot from 'uplot'

import uPlotTooltipPlugin from './uplot-tooltip-plugin'

import 'uplot/dist/uPlot.min.css'

function createSeriesConf(item, index) {
  return { label: item.id, stroke: item.color, spanGaps: true }
}

class SingleChart extends React.PureComponent {
  componentDidMount() {
    this.init(this.props)
  }

  init({ series, id } = this.props) {
    const options = {
      // title: 'Scale range exceeds data range (zoom out)',
      width: 400,
      height: 300,
      series: series.label.map(createSeriesConf),
      scales: {
        x: {
          time: false
        }
      },
      bands: series.bands,
      plugins: [uPlotTooltipPlugin()],
      legend: {
        show: false
      },
      drawOrder: ['series', 'axes'],
      axes: [
        {
          grid: {
            show: true,
            stroke: 'rgba(0,0,0,0.2)',
            width: 1
          }
        },
        {
          grid: {
            show: true,
            stroke: 'rgba(0,0,0,0.2)',
            width: 1
          }
        }
      ]
    }
    this.chart = new uPlot(options, series.list, document.getElementById(id))
  }

  destroy() {
    if (this.chart) {
      this.chart.destroy()
    }
  }

  reInit(nextProps = this.props) {
    this.destroy()

    this.init(nextProps)
  }

  updateSeries(nextProps) {
    if (!this.chart) return

    for (let i = this.chart.series.length - 1; i >= 0; i--) {
      this.chart.delSeries(i)
    }
    // add series
    nextProps.series.label.map((item, index) => {
      this.chart.addSeries(createSeriesConf(item, index))
    })

    if (this.chart.bands.length > 0) {
      this.chart.bands.length = 0
      this.chart.bands.push.apply(this.chart.bands, nextProps.series.bands)
    }

    this.chart.setData(nextProps.series.list)
  }

  componentWillUnmount() {
    this.destroy()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.series) {
      const diffCount =
        nextProps.series.list.length - this.props.series.list.length

      if (diffCount === 0) {
        this.chart.setData(nextProps.series.list)
      }
      // this.reInit()
      this.updateSeries(nextProps)
    }
  }

  render() {
    return pug`
      div(id=this.props.id style={ width: '400px', height: '300px'})
    `
  }
}

export default SingleChart
